<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>三级菜单</title>
    <link rel="stylesheet" href="../css/common.css">
    <style>
        #menu {
            width: 200px;
            margin: 20px;
        }

        .province {
            cursor: pointer;
        }

        .title {
            height: 30px;
            text-align: center;
            background-color: #369;
            color: white;
            line-height: 30px;
            font-size: 18px;
        }

        .city>li {
            height: 30px;
            text-align: center;
            background-color: rgb(81, 153, 189);
            color: white;
            line-height: 30px;
            position: relative;
        }

        .city>li:hover>.district {
            display: block;
        }

        .district {
            background-color: rgb(122, 173, 199);
            color: white;
            position: absolute;
            top: 0px;
            left: 200px;
            width: 200px;
            display: none;
        }
    </style>
</head>

<body>
    <div id="menu">
        <script id="province_temp" type="text/html">
        {{each $data p}}
        <div class="province">
            <div class="title">{{p.name}}</div>
            {{each p.citys c}}
            <ul class="city">
                <li>{{c.name}}
                    <ul class="district">
                        {{each c.districts d}}
                        <li>{{d.name}}</li>
                        {{/each}}
                    </ul>
                </li>
            </ul>
            {{/each}}
        </div>
        {{/each}}
        </script>
    </div>
    <script src="./js/artTemplate.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.js"></script>
    <script>
        //定义一个省份数组
        let provinces = []
        //加载数据的方法
        function loadData() {
            $.get('./data/city.json', res => {
                //先从原始数据中获取所有的省份信息
                provinces = res.filter(r => r.pid === 0)
                //循环省份数组
                provinces.forEach(p => {
                    //给每个省份对象，添加一个城市数组
                    p.citys = res.filter(r => r.pid === p.id)
                    //循环每个省份里面的城市数组
                    p.citys.forEach(c => {
                        //给每个城市对象，添加一个区县数组
                        c.districts = res.filter(r => r.pid === c.id)
                    })
                })
                //调用模板，生成页面
                $("#menu").html(template('province_temp',provinces))
            })
        }
        //调用加载数据的方法
        loadData();
    </script>
</body>

</html>